<template>
  <div class="data-main">
    <el-row>
      <el-col :span="5">
        <div class="data-left">
          <div
            v-for="attribute in deviceAttributes"
            :key="attribute.token"
            @click="changeStyle(attribute.token)"
          >
            <div
              class="data-param"
              :class="{ bg_style: index_token == attribute.token }"
            >
              <div>
                <div
                  class="data-img"
                  :class="{ bg_img: index_token == attribute.token }"
                />
              </div>
              <div class="param-text">
                <div
                  class="text-key"
                  :class="{ bg_color: index_token == attribute.token }"
                >
                  {{ attribute.name }}
                </div>
                <div
                  class="text-value"
                  :class="{ bg_color: index_token == attribute.token }"
                >
                  {{ attribute.dataValue }}{{ attribute.unit }}
                </div>
              </div>
            </div>
          </div>
          <div class="smallPaging">
            <el-pagination
              v-if="total > 0"
              small
              layout="prev, pager, next"
              :current-page.sync="page"
              :page-size.sync="pageSize"
              :total="total"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </el-col>
      <el-col :span="19">
        <div class="data-right">
          <div ref="chart" class="chart" />
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { formatTime2 } from "@/views/common/js/utils.js";
import { formatDate } from "@/filter/index";
import initMqtt from "@/views/common/js/device/mqttUtils.js";
import {
  echartOptionInit,
  echartOptionLine
} from "@/views/common/js/device/echartsUtils.js";
import { getDeviceTypeAttributes } from "@/api/deviceType";
export default {
  props: {
    deviceToken: {
      type: String
    },
    deviceTypeToken: {
      type: String
    }
  },
  data() {
    return {
      page: 1,
      pageSize: 3,
      total: 0,
      index_token: "",
      initmqtt: "",
      client: "",
      tenantTopic: "",
      lineChart: {},
      option: {},
      xData: [],
      yData: [],
      lend: "",
      deviceAttributes: [],
      attributeSelectTokens: []
    };
  },
  mounted() {},
  created() {},
  destroyed() {
    // 页面关闭,关闭mqtt连接
    if (this.client) {
      this.client.end();
    }
  },
  methods: {
    // 页面数据初始化
    init() {
      this.getDeviceRunTimeData();
      if (this.client == "") {
        this.receiveData();
        this.drawLine();
      }
    },
    // 执行参数过滤
    handleParamsFilter() {
      this.page = 1;
      this.clearLineData();
      this.getDeviceRunTimeData();
    },
    // 获取点位列表
    getDeviceRunTimeData() {
      var params = {
        page: this.page,
        pageSize: this.pageSize,
        attributeTokenList: this.attributeSelectTokens
      };
      getDeviceTypeAttributes(params, this.deviceTypeToken).then(res => {
        const r = res.data;
        // 必须先添加value属性,否则后面不会实时响应变化
        this.deviceAttributes = [];
        r.results.forEach(v => {
          v.dataValue = "";
          if (v.name.indexOf("百分比") > 0) {
            v.unit = "%"; // 单位
          } else if (v.name.indexOf("温度") > 0) {
            v.unit = "℃";
          } else {
            v.unit = "";
          }
          this.deviceAttributes.push(v);
        });
        this.total = r.numResults;
        if (this.deviceAttributes.length > 0) {
          this.index_token = this.deviceAttributes[0].token;
        }
      });
    },
    // 分页调用
    handleCurrentChange(val) {
      this.page = val;
      this.index_token = "";
      this.clearLineData();
      this.getDeviceRunTimeData();
    },
    // 切换点位
    changeStyle(token) {
      if (this.index_token != token) {
        this.index_token = token;
        this.clearLineData();
      }
    },
    // mqtt接收数据
    receiveData() {
      var param = {
        url: process.env.VUE_APP_MQTT_WS_URL + "/mqtt"
      };
      this.tenantToken = this.$store.state.user.tenant.token;
      this.tenantTopic = `$avic/superlink/iot/${this.tenantToken}/${this.deviceToken}/measurement`;
      console.log("this.tenantTopic :>> ", this.$store.state.user.tenant.token);
      this.initmqtt = new initMqtt(param);
      this.client = this.initmqtt.connect(() => {
        console.log("mqtt连接成功,开始订阅主题");
        this.client.subscribe(this.tenantTopic);
        this.onMessageArrived();
      });
    },
    // 接收数据
    onMessageArrived() {
      this.client.on("message", (topic, message) => {
        console.log(message, "==================");
        var obj = JSON.parse(message.toString());
        if (obj.type == "DeviceMeasurement") {
          if (obj.deviceToken == this.deviceToken) {
            var metadata = obj.request.metadata;
            for (var index in metadata) {
              // echarts中数据添加
              if (this.index_token == index) {
                this.xData.push(
                  formatDate(obj.request.eventDate, "HH:mm:ss", true)
                );
                this.yData.push(metadata[index]);
                this.drawLineData();
                // 暂时只保留1800条数据
                if (this.yData.length > 1800) {
                  this.xData.splice(0, 1);
                  this.yData.splice(0, 1);
                }
              }
              // 点位列表中实时数据
              this.deviceAttributes.forEach(v => {
                if (v.token == index) {
                  if (metadata[index] === "true") {
                    v.dataValue = "开启";
                  } else if (metadata[index] === "false") {
                    v.dataValue = "关闭";
                  } else {
                    v.dataValue = metadata[index];
                  }
                }
              });
            }
          }
        }
      });
    },

    // 折线图初始化
    drawLine() {
      const that = this;
      // 基于准备好的dom，初始化echarts实例
      this.lineChart = this.$echarts.init(this.$refs.chart);
      this.option = echartOptionInit(20, 180);
      // 绘制图表
      this.lineChart.setOption(this.option);
      // 随浏览器变化响应大小
      window.onresize = function() {
        that.lineChart.resize();
      };
    },

    // 添加数据
    drawLineData() {
      this.option = echartOptionLine(this.xData, this.yData);
      // 绘制图表
      this.lineChart.setOption(this.option);
      // /this.lineChart.resize();
    },
    // 清理折线图原有数据
    clearLineData() {
      this.xData = [];
      this.yData = [];
      this.option = echartOptionLine(this.xData, this.yData);
      this.option.title = {
        text: "暂无数据",
        left: 7,
        textStyle: {
          color: "#CCCCCC",
          fontSize: 16
        }
      };
      // 绘制图表
      this.lineChart.setOption(this.option);
    }
  }
};
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";
.data-main {
  /* margin: 16px 0 20px 16px; */
  padding: 20px;
  padding-bottom: 0;
}
.data-param {
  display: flex;
  justify-content: space-between;
  flex-direction: column;
  padding: 15px;
  height: 62px;
  border: 1px solid #e4e4e4;
  margin-bottom: 8px;
  background: #f5f5f5;
  cursor: pointer;
}
.param-text {
  margin: -40px 0 0 46px;
}
.text-key {
  font-size: 12px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  line-height: 22px;
  color: #999999;
}
.text-value {
  @include textoverflow(1);
  font-size: 18px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  line-height: 22px;
  color: #cccccc;
}
.data-img {
  width: 33px;
  height: 30px;
  background-image: url("../../../assets/images/comm/param-unselect.png");
}
.bg_style {
  background-color: #f2fbff !important;
  border: 1px solid #2680d2 !important;
}
.bg_color {
  color: #2680d2 !important;
}
.bg_img {
  width: 33px;
  height: 30px;
  background-image: url("../../../assets/images/comm/param-select.png");
}
.chart {
  height: 230px;
}

// 分页样式自定义
.smallPaging {
  /* margin-left: 33%; */
  width: 100%;
  text-align: center;
}
/deep/.smallPaging .el-pagination .btn-prev {
  display: none;
}
/deep/.smallPaging .el-pagination .btn-next {
  display: none;
}
/deep/.smallPaging .el-pager li.active {
  cursor: default;
  height: 8px;
  border-radius: 50%;
  background: #2680d2;
  min-width: 0px;
  width: 8px;
  color: #fff;
}
/deep/.smallPaging .el-pager li {
  min-width: 0px;
  width: 8px;
  height: 8px;
  background: #cccccc;
  border-radius: 50%;
  color: #ccc;
  margin-left: 8px;
  font-size: 0px;
}
/deep/.smallPaging .el-pager li:last-child {
  height: 8px;
  min-width: 0;
  font-size: 0px;
}
/deep/.smallPaging .el-pager li:hover {
  color: #2680d2;
  background-color: #2680d2;
}
/deep/.smallPaging .el-pager li.active {
  font-size: 0px;
}
</style>
